/*
 * @Description:
 * @Author: fhw
 * @Date: 2023-02-17 13:58:56
 */
import {
  Body,
  Controller,
  HttpCode,
  Post,
  UseGuards,
  Headers,
  Get,
  Query,
  Request,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import {
  ApiQuery,
  ApiBody,
  ApiOperation,
  ApiResponse,
  ApiTags,
  ApiBearerAuth,
} from '@nestjs/swagger';
import { Roles } from 'src/common/auth/role.decorator';
import { throwHttp } from 'src/utlis';
import { isTrue } from 'src/utlis/tools';
import { RoleEntity } from '../role/entities/role.entity';
import { AdminUserService } from './admin-user.service';
import {
  UpdataAdminPassWordDto,
  ValidateAdminUserDto,
  RegisterAdminUserDto,
  DelteIdDto,
  AdminUserBindRoleDto,
  GetAdminUserPage,
  UpdateAdminUserDto,
} from './dto/admin-user.dto';
import {
  AdminUser,
  AdminUserFieldName,
  AdminUserResult,
} from './entities/admin-user.entity';
import { TokenDto } from 'src/common/auth/constants';
import { AuthGuard } from '@nestjs/passport';
import {
  MethodType,
  OperateType,
  OperationRecordType,
} from '../operation-record/entities/operation-record.entity';
import { OperationRecordService } from '../operation-record/operation-record.service';
import { LogOperation } from '../operation-record/log.decorator';
@ApiBearerAuth() // swagger文档设置token
@ApiTags('后台管理用户')
@Controller('admin/admin-user')
export class AdminUserController {
  constructor(
    private readonly adminUserService: AdminUserService,
    private readonly operationRecordService: OperationRecordService,
    private readonly jwtService: JwtService,
  ) { }
  /** 后台用户列表 */
  @HttpCode(200)
  @Get('/getAdminUserPage')
  @ApiResponse({
    status: 200,
    description: '后台用户列表',
    type: AdminUserResult,
  })
  @ApiOperation({
    tags: ['获取后台用户列表'],
    summary: '获取后台用户列表',
    operationId: 'getAdminUserPage',
  })
  @UseGuards(AuthGuard('jwt')) // 自定义守卫
  getAdminUserPage(@Query() params: GetAdminUserPage) {
    return this.adminUserService.getAdminUserPage(params);
  }
  @HttpCode(200)
  @Post('/registerAdminUser')
  @ApiBody({ description: '用户注册', type: RegisterAdminUserDto })
  @ApiOperation({ summary: '用户注册', operationId: 'registerAdminUser' })
  @ApiResponse({ status: 200, type: AdminUser })
  @UseGuards(AuthGuard('jwt')) // 自定义守卫
  registerAdminUser(@Body() body: RegisterAdminUserDto) {
    return this.adminUserService.registerAdminUser(body);
  }
  @HttpCode(200)
  @Post('/login')
  @ApiBody({ description: '登录', type: ValidateAdminUserDto })
  @ApiOperation({ summary: '登录', operationId: 'login' })
  async login(@Body() body: ValidateAdminUserDto, @Request() req) {
    try {
      const data = await this.adminUserService.login(body);
      // 操作记录
      await this.operationRecordService.createOperationRecord(
        {
          operation: `登录成功, IP:${req.ip}`,
          name: '登录',
          method: MethodType.POST,
          outside: OperationRecordType.adminUser,
          operateType: OperateType.login,
          interfacePath: 'admin/admin-user/login',
          ip: req.ip,
          dataId: data.id,
        },
        data.id,
      );
      return data;
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 用户详情 */
  @HttpCode(200)
  @Get('/getUserInfo')
  @ApiResponse({
    status: 200,
    description: '用户详情',
    type: AdminUser,
  })
  @ApiOperation({
    tags: ['获取用户详情'],
    summary: '获取用户详情',
    operationId: 'getUserInfo',
  })
  @UseGuards(AuthGuard('jwt')) // 自定义守卫
  async getUserInfo(@Headers('authorization') authorization) {
    if (!isTrue(authorization)) {
      throwHttp('获取token失败');
    }
    const token = authorization.split(' ');
    const user: TokenDto = this.jwtService.decode(token[1]) as TokenDto;
    const data = await this.adminUserService.getUserInfo({
      id: user.userId,
    });
    data.roles = data.roles?.rolename as any;
    return data;
  }
  @HttpCode(200)
  @Post('/updatePassWord')
  @ApiBody({ description: '修改密码', type: UpdataAdminPassWordDto })
  @ApiOperation({ summary: '修改密码', operationId: 'updatePassWord' })
  @UseGuards(AuthGuard('jwt')) // 自定义守卫
  @ApiResponse({ status: 200, type: String })
  @LogOperation(
    {
      operateType: OperateType.edit,
      operation: `修改密码`,
      name: '修改密码',
      outside: OperationRecordType.adminUser,
      entity: AdminUser,
    },
    {
      dataIdKey: 'dataId',
    },
  )
  async updatePassWord(
    @Headers('authorization') authorization,
    @Body() body: UpdataAdminPassWordDto,
    @Request() req,
  ) {
    if (!isTrue(authorization)) {
      throwHttp('获取token失败');
    }
    // 操作记录
    const data = await this.adminUserService.updatePassWord(body);
    return data.msg;
  }
  @HttpCode(200)
  @Post('/resetPassWord')
  @ApiBody({ description: '重置密码', type: DelteIdDto })
  @ApiOperation({ summary: '重置密码', operationId: 'resetPassWord' })
  @UseGuards(AuthGuard('jwt')) // 自定义守卫
  @ApiResponse({ status: 200, type: String })
  @LogOperation(
    {
      operateType: OperateType.other,
      operation: `重置密码`,
      name: '重置密码',
      outside: OperationRecordType.adminUser,
      entity: AdminUser,
    },
  )
  async resetPassWord(
    @Headers('authorization') authorization,
    @Request() req,
    @Body() body: DelteIdDto,
  ) {
    if (!isTrue(authorization)) {
      throwHttp('获取token失败');
    }
    const token = authorization.split(' ');
    const data = await this.adminUserService.resetPassWord(body);
    return data.msg;
  }

  @HttpCode(200)
  @Post('/delAdminUser')
  @ApiBody({ description: '删除用户', type: DelteIdDto })
  @ApiOperation({ summary: '删除用户', operationId: 'delAdminUser' })
  @Roles('admin') // 自定义装璜器
  @UseGuards(AuthGuard('jwt')) // 自定义守卫
  async delAdminUser(
    @Headers('authorization') authorization,
    @Request() req,
    @Body() body: DelteIdDto,
  ) {
    if (!isTrue(authorization)) {
      throwHttp('获取token失败');
    }
    const token = authorization.split(' ');
    const user: TokenDto = this.jwtService.decode(token[1]) as TokenDto;
    const data = await this.adminUserService.delAdminUser(body);
    await this.operationRecordService.createOperationRecord(
      {
        operation: `删除用户: ${data.data.username}`,
        name: '删除用户',
        method: MethodType.POST,
        outside: OperationRecordType.adminUser,
        operateType: OperateType.delete,
        interfacePath: 'admin/admin-user/delAdminUser',
        ip: req.ip,
        dataId: body.id,
      },
      user.userId,
    );
    return data.msg;
  }
  /** 用户角色 */
  @HttpCode(200)
  @Get('/getUserRole')
  @ApiResponse({
    status: 200,
    description: '用户角色',
    type: [RoleEntity],
  })
  @ApiOperation({
    tags: ['获取用户角色'],
    summary: '获取用户角色',
    operationId: 'getUserRole',
  })
  @UseGuards(AuthGuard('jwt')) // 自定义守卫
  getUserRole(@Headers('authorization') authorization) {
    if (!isTrue(authorization)) {
      throwHttp('获取token失败');
    }
    const token = authorization.split(' ');
    const user: TokenDto = this.jwtService.decode(token[1]) as TokenDto;
    return this.adminUserService.getUserRole(user);
  }
  @HttpCode(200)
  @Post('/adminUserBindRole')
  @ApiBody({ description: '绑定用户角色', type: AdminUserBindRoleDto })
  @ApiOperation({ summary: '绑定用户角色', operationId: 'adminUserBindRole' })
  @UseGuards(AuthGuard('jwt')) // 自定义守卫
  async adminUserBindRole(
    @Headers('authorization') authorization,
    @Request() req,
    @Body() body: AdminUserBindRoleDto,
  ) {
    if (!isTrue(authorization)) {
      throwHttp('获取token失败');
    }
    const token = authorization.split(' ');
    const user: TokenDto = this.jwtService.decode(token[1]) as TokenDto;
    const data = await this.adminUserService.adminUserBindRole(body);
    if (body.diff) {
      const diff = this.operationRecordService.convertToChinese(
        body.diff as any[],
        AdminUserFieldName,
      );
      await this.operationRecordService.createOperationRecord(
        {
          operation: diff,
          name: '绑定用户角色',
          method: MethodType.POST,
          outside: OperationRecordType.adminUser,
          operateType: OperateType.add,
          interfacePath: 'admin/admin-user/adminUserBindRole',
          ip: req.ip,
          dataId: body.userId,
        },
        user.userId,
      );
    }
    return data;
  }
  @HttpCode(200)
  @Post('/updateAdminUser')
  @ApiBody({ description: '更新用户信息', type: UpdateAdminUserDto })
  @ApiOperation({ summary: '更新用户信息', operationId: 'updateAdminUser' })
  @UseGuards(AuthGuard('jwt')) // 自定义守卫
  @LogOperation(
    {
      operateType: OperateType.edit,
      operation: `更新用户信息`,
      name: '更新用户信息',
      outside: OperationRecordType.adminUser,
      entity: AdminUser,
    },
    {
      dataIdKey: 'userId',
    },
  )
  async updateAdminUser(
    @Headers('authorization') authorization,
    @Request() req,
    @Body() body: UpdateAdminUserDto,
  ) {
    if (!isTrue(authorization)) {
      throwHttp('获取token失败');
    }
    const token = authorization.split(' ');
    const user: TokenDto = this.jwtService.decode(token[1]) as TokenDto;
    // if (body.diff) {
    //   const diff = this.operationRecordService.convertToChinese(
    //     body.diff as any[],
    //     AdminUserFieldName,
    //   );
    //   await this.operationRecordService.createOperationRecord(
    //     {
    //       operation: diff,
    //       name: '更新用户信息',
    //       method: MethodType.POST,
    //       outside: OperationRecordType.adminUser,
    //       operateType: OperateType.edit,
    //       interfacePath: 'admin/admin-user/updateAdminUser',
    //       ip: req.ip,
    //       dataId: body.userId,
    //     },
    //     user.userId,
    //   );
    // }
    return this.adminUserService.updateAdminUser(body);
  }
}
